<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <div class="content">

            <div class="progressHint" v-if="hint">
              <NIcon size="20" class="iconStyle">
                <ErrorRound />
              </NIcon>
              <div style="white-space: pre-wrap" v-html="hint"></div>
            </div>
            <div class="progress">
              <div style="display:flex; margin-right: 10rem;">
                <NIcon :size="20" class="iconStyle">
                  <ApprovalFilled />
                </NIcon>
                <span>审批流程</span>
              </div>
              <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
                {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
              </span>
            </div>

            <div class="content_cen">
              <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="110"
                :model="formValue" label-align="right" style="width: 350rem;">
                <NFormItem label="项目名称:" path="projectName">
                  <NInput placeholder="请输入项目名称" class="commonWidth" v-model:value="formValue.projectName" clearable
                    :allow-input="noSideSpace" />
                </NFormItem>

                <NFormItem label="项目内容:" path="projectContent">
                  <NInput placeholder="请输入项目内容" style="min-height: 100rem" type="textarea"
                    v-model:value="formValue.projectContent" clearable class="commonWidth" :allow-input="noSideSpace" />
                </NFormItem>

                <NFormItem label="劳务类型:" path="laborType">
                  <NSelect :options="[
                    { label: '非稿酬', value: '0' },
                    { label: '稿酬', value: '1' }
                  ]" placeholder="请选择劳务类型" clearable class="commonWidth" v-model:value="formValue.laborType"
                    @update-value="handleLaborType" />
                </NFormItem>

                <NFormItem label="税前合计金额:" path="amount">
                  <NScrollbar x-scrollable>
                    <div class="amountClass">{{ useStore.convertToRMB(formValue.amount) }}</div>
                  </NScrollbar>
                </NFormItem>

                <NFormItem label="附件:" path="fileId">
                  <VUpload :file-list="fileList" @getList="handleUploadList" />
                </NFormItem>

                <NFormItem label="" :show-feedback="false">
                  <div style="width: 100%;display: flex;justify-content: flex-start;">
                    <NButton type="primary" style="margin-right: 10rem;width: 140rem;" @click="IssuerAdd">添加发放人</NButton>
                    <NButton type="primary" style="width: 140rem;" @click="openIssuer">选择常用发放人</NButton>
                  </div>
                </NFormItem>

                <!-- 发放人 -->
                <NSpace style="margin-top: 10px;width: 100%;position: relative;margin-bottom: 50px;"
                  v-for="(item, index) in  formValue.laborInfoList " :key="index">
                  <div
                    style="font-weight: bold;font-size: 18px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif;">
                    发放人{{ index + 1 }}
                  </div>

                  <NForm ref="formRefUser" require-mark-placement="left" label-placement="left" :label-width="110"
                    :model="formValue" label-align="right" style="width: 350rem;">

                    <NFormItem label="姓名:" :path="`laborInfoList[${index}]['name']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderName(_, value)
                    }
                      ">
                      <NInput placeholder="请输入姓名" class="commonWidth" v-model:value="item.name" clearable />
                    </NFormItem>

                    <NFormItem label="身份证号:" :path="`laborInfoList[${index}]['idCard']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderIdCard(_, value)
                    }
                      ">
                      <NInput placeholder="请输入身份证号" class="commonWidth" v-model:value="item.idCard" clearable />
                    </NFormItem>

                    <NFormItem label="职称:" :path="`laborInfoList[${index}]['duty']`" :rule="{
                      required: true,
                      message: '请选择职称',
                      trigger: ['select', 'change', 'blur']
                    }
                      ">
                      <NSelect :options="parentCodeList" placeholder="请选择职称" clearable class="commonWidth"
                        v-model:value="item.duty" label-field="dicName" value-field="dicCode" />
                    </NFormItem>

                    <NFormItem label="时长:" :path="`laborInfoList[${index}]['duration']`" :rule="{
                      required: true,
                      message: '请输入时长',
                      trigger: ['input', 'change', 'blur']
                    }
                      ">
                      <NInput placeholder="请输入时长" class="commonWidth" v-model:value="item.duration" clearable />
                    </NFormItem>

                    <NFormItem label="税前金额:" :path="`laborInfoList[${index}]['salary']`" :rule="{
                      required: true,
                      message: '请输入税前金额',
                      trigger: ['input', 'change', 'blur']
                    }
                      ">
                      <NInput placeholder="请输入税前金额" class="commonWidth" v-model:value="item.salary" clearable
                        :allow-input="onlyFloatNumber" @blur="handleTax(index, true)" />
                    </NFormItem>

                    <NFormItem label="预扣个税:" :path="`laborInfoList[${index}]['tax']`" :rule="{
                      required: false,
                      message: '请输入预扣个税',
                      trigger: ['input', 'change']
                    }
                      ">
                      <NInput v-if="formValue.laborType == 1" placeholder="预扣个税" class="commonWidth"
                        v-model:value="item.tax" clearable :allow-input="onlyFloatNumber" />
                      <NInput v-else placeholder="预扣个税" class="commonWidth" v-model:value="item.tax" clearable disabled />
                    </NFormItem>

                    <NFormItem label="预后所得:" :path="`laborInfoList[${index}]['acquire']`" :rule="{
                      required: false,
                      message: '请输入预后所得',
                      trigger: ['input', 'change']
                    }
                      ">
                      <NInput v-if="formValue.laborType == 1" placeholder="预后所得" class="commonWidth"
                        v-model:value="item.acquire" clearable :allow-input="onlyFloatNumber" />
                      <NInput v-else placeholder="预后所得" class="commonWidth" v-model:value="item.acquire" clearable
                        disabled />
                    </NFormItem>

                    <NFormItem label="开户银行:" :path="`laborInfoList[${index}]['bankName']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderBankName(_, value)
                    }
                      ">
                      <NInput placeholder="请输入开户银行" class="commonWidth" v-model:value="item.bankName" clearable />
                    </NFormItem>

                    <NFormItem label="银行卡号:" :path="`laborInfoList[${index}]['bankId']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderBankId(_, value)
                    }
                      ">
                      <NInput placeholder="请输入银行卡号" class="commonWidth" v-model:value="item.bankId" clearable />
                    </NFormItem>

                    <NFormItem label="手机号码:" :path="`laborInfoList[${index}]['phone']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderPhone(_, value)
                    }
                      ">
                      <NInput placeholder="请输入手机号码" class="commonWidth" v-model:value="item.phone" clearable />
                    </NFormItem>

                    <NFormItem label=" " :show-feedback="false">
                      <div style="display: flex;justify-content: center;align-items: center;width: 240rem;">
                        <NButton type="primary" style="width: 140px;" @click="SaveIssuer(index, true)" ghost>保存为常用发放人
                        </NButton>
                      </div>
                    </NFormItem>
                  </NForm>

                  <div class="delectIcon" v-if="(formValue.laborInfoList.length + formValue.customIssuer?.length) != 1"
                    @click="deleteIssuer(index)">—</div>
                </NSpace>

                <!-- 常用发放人 -->
                <NSpace style="margin-top: 10px;width: 100%;position: relative;margin-bottom: 50px;"
                  v-for="(item, index) in formValue.customIssuer " :key="index">
                  <div
                    style="font-weight: bold;font-size: 18px; font-family: Helvetica Neue, Helvetica, Arial, sans-serif;">
                    发放人{{ formValue.laborInfoList?.length + index + 1 }}
                  </div>

                  <NForm ref="formRefIssuer" require-mark-placement="left" label-placement="left" :label-width="110"
                    :model="formValue" label-align="right" style="width: 350rem;">

                    <NFormItem label="姓名:" :path="`customIssuer[${index}]['name']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderName(_, value)
                    }
                      ">
                      <NInput placeholder="请输入姓名" class="commonWidth" v-model:value="item.name" clearable />
                    </NFormItem>

                    <NFormItem label="身份证号:" :path="`customIssuer[${index}]['idCard']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderIdCard(_, value)
                    }
                      ">
                      <NInput placeholder="请输入身份证号" class="commonWidth" v-model:value="item.idCard" clearable />
                    </NFormItem>

                    <NFormItem label="职称:" :path="`customIssuer[${index}]['duty']`" :rule="{
                      required: true,
                      message: '请选择职称',
                      trigger: ['select', 'change', 'blur']
                    }
                      ">
                      <NSelect :options="parentCodeList" placeholder="请选择职称" clearable class="commonWidth"
                        v-model:value="item.duty" label-field="dicName" value-field="dicCode" />
                    </NFormItem>

                    <NFormItem label="时长:" :path="`customIssuer[${index}]['duration']`" :rule="{
                      required: true,
                      message: '请输入时长',
                      trigger: ['input', 'change', 'blur']
                    }
                      ">
                      <NInput placeholder="请输入时长" class="commonWidth" v-model:value="item.duration" clearable />
                    </NFormItem>

                    <NFormItem label="税前金额:" :path="`customIssuer[${index}]['salary']`" :rule="{
                      required: true,
                      message: '请输入税前金额',
                      trigger: ['input', 'change', 'blur']
                    }
                      ">
                      <NInput placeholder="请输入税前金额" class="commonWidth" v-model:value="item.salary" clearable
                        :allow-input="onlyFloatNumber" @blur="handleTax(index, false)" />
                    </NFormItem>

                    <NFormItem label="预扣个税:" :path="`customIssuer[${index}]['tax']`" :rule="{
                      required: false,
                      message: '请输入预扣个税',
                      trigger: ['input', 'change']
                    }
                      ">
                      <NInput v-if="formValue.laborType == 1" placeholder="预扣个税" class="commonWidth"
                        v-model:value="item.tax" clearable :allow-input="onlyFloatNumber" />
                      <NInput v-else placeholder="预扣个税" class="commonWidth" v-model:value="item.tax" clearable disabled />
                    </NFormItem>

                    <NFormItem label="预后所得:" :path="`customIssuer[${index}]['acquire']`" :rule="{
                      required: false,
                      message: '请输入预后所得',
                      trigger: ['input', 'change']
                    }
                      ">
                      <NInput v-if="formValue.laborType == 1" placeholder="预后所得" class="commonWidth"
                        v-model:value="item.acquire" clearable :allow-input="onlyFloatNumber" />
                      <NInput v-else placeholder="预后所得" class="commonWidth" v-model:value="item.acquire" clearable
                        disabled />
                    </NFormItem>

                    <NFormItem label="开户银行:" :path="`customIssuer[${index}]['bankName']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderBankName(_, value)
                    }
                      ">
                      <NInput placeholder="请输入开户银行" class="commonWidth" v-model:value="item.bankName" clearable />
                    </NFormItem>

                    <NFormItem label="银行卡号:" :path="`customIssuer[${index}]['bankId']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderBankId(_, value)
                    }
                      ">
                      <NInput placeholder="请输入银行卡号" class="commonWidth" v-model:value="item.bankId" clearable />
                    </NFormItem>

                    <NFormItem label="手机号码:" :path="`customIssuer[${index}]['phone']`" :rule="{
                      required: true,
                      trigger: ['input', 'change', 'blur'],
                      validator: (_, value) => renderPhone(_, value)
                    }
                      ">
                      <NInput placeholder="请输入手机号码" class="commonWidth" v-model:value="item.phone" clearable />
                    </NFormItem>

                    <NFormItem label=" " :show-feedback="false">
                      <div style="display: flex;justify-content: center;align-items: center;width: 240rem;">
                        <NButton type="primary" style="width: 140px;" @click="SaveIssuer(index, false)" ghost>保存为常用发放人
                        </NButton>
                      </div>
                    </NFormItem>
                  </NForm>

                  <div class="delectIcon" v-if="(formValue.laborInfoList.length + formValue.customIssuer?.length) != 1"
                    @click="deleteCustomIssuer(index)">—</div>
                </NSpace>
              </NForm>
            </div>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(true)" :loading="loading"
          v-if="formValue.entityId">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(false)" :loading="loading" v-if="formValue.entityId">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="contentVisible" @close="contentVisible = false">
    <VDialogContent @close="contentVisible = false" @submit="submit" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>

  <NModal :auto-focus="false" v-model:show="customVisiable">
    <CustomVisitor @close="customVisiable = false" :customIds="customIds" @update="handleCustom" />
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import {
  NSpace, NForm, NInput, NFormItem, NSelect, NButton, NScrollbar, NModal, NIcon,
  useMessage, NSpin, type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import VUpload from '@/views/OA/Common/Upload.vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponse } from '@/utils/http'
import type { OverTimeModel } from '@/api/overTime'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { ApprovalFilled } from '@vicons/material'
import VBackImg from '@/assets/images/back.png'
import { ErrorRound } from '@vicons/material'
import CustomVisitor from './CustomVisitor.vue'
import { useViewerStore } from '@/views/OA/Common/store'
import { cardNumberRegex } from '@/enums/regex'

const useStore = useViewerStore()
const tags = useTagStore().tags
const props = defineProps({
  title: { type: String, default: () => '劳务费申请' },
  id: { type: [Number, String], default: () => null },
  flat: { default: () => false }
})
const message = useMessage()

const formValue = reactive<Record<string, any>>({
  projectName: null, //项目名称
  projectContent: null, //项目内容
  laborType: null, //劳务类型
  amount: '0', //税前合计金额
  fileId: null, //附件
  draft: null, //草稿状态
  entityId: null, //流程实体id
  laborInfoList: [], // 发放人信息
  customIssuer: [] // 常用发放人信息
})
const rules = {
  projectName: {
    required: true,
    trigger: ['input', 'change', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入项目名称')
      if (value?.length > 100) return new Error('项目名称字数不得超过100')
      return true
    }
  },
  projectContent: {
    required: true,
    trigger: ['input', 'change', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入项目内容')
      if (value?.length > 500) return new Error('项目内容字数不得超过500')
      return true
    }
  },
  laborType: {
    required: true,
    message: '请选择劳务类型',
    trigger: ['select', 'change']
  }
}
// 选择劳务类型
const handleLaborType = (val: any) => {
  formValue.laborType = val
  if (val) {
    formValue.laborInfoList.map((it: any) => {
      it.tax = '0'
      it.acquire = '0'
    })
    formValue.customIssuer.map((it: any) => {
      it.tax = '0'
      it.acquire = '0'
    })
  }
}
//确定常用访客
const customVisiable = ref(false)
const customIds = ref()
const handleCustom = (info: any) => {
  setTimeout(async () => {
    info.forEach((it: any, i: any) => {
      const index = formValue.customIssuer.findIndex((c: any) => c.name == it.name && c.phone == it.phone)
      if (index == -1) formValue.customIssuer.push(info[i])
    })
  }, 0)
  handleAmount()
}
// 打开选择常用发放人
const openIssuer = () => {
  customIds.value = formValue.customIssuer.map((it: any) => it.id)
  customVisiable.value = true
}
// 处理预扣个税/预计所得
const handleTax = (index: number, flag: any) => {
  if (formValue.laborType == '1') return handleAmount()
  if (flag) {
    const salary = formValue.laborInfoList[index].salary
    if (0 <= salary && salary <= 800) formValue.laborInfoList[index].tax = '0'
    if (800 < salary && salary <= 4000) formValue.laborInfoList[index].tax = ((salary - 800) * 0.2).toFixed(2).toString()
    if (4000 < salary && salary <= 25000) formValue.laborInfoList[index].tax = (salary * 0.8 * 0.2).toFixed(2).toString()
    if (25000 < salary && salary <= 62500) formValue.laborInfoList[index].tax = (salary * 0.8 * 0.3 - 2000).toFixed(2).toString()
    if (salary > 62500) formValue.laborInfoList[index].tax = (salary * 0.8 * 0.4 - 7000).toFixed(2).toString()
    // 预后所得
    formValue.laborInfoList[index].acquire = (salary - formValue.laborInfoList[index].tax).toFixed(2).toString()
    handleAmount()
  } else {
    const salary = formValue.customIssuer[index].salary
    if (0 <= salary && salary <= 800) formValue.customIssuer[index].tax = '0'
    if (800 < salary && salary <= 4000) formValue.customIssuer[index].tax = ((salary - 800) * 0.2).toFixed(2).toString()
    if (4000 < salary && salary <= 25000) formValue.customIssuer[index].tax = (salary * 0.8 * 0.2).toFixed(2).toString()
    if (25000 < salary && salary <= 62500) formValue.customIssuer[index].tax = (salary * 0.8 * 0.3 - 2000).toFixed(2).toString()
    if (salary > 62500) formValue.customIssuer[index].tax = (salary * 0.8 * 0.4 - 7000).toFixed(2).toString()
    // 预后所得
    formValue.customIssuer[index].acquire = (salary - formValue.customIssuer[index].tax).toFixed(2).toString()
    handleAmount()
  }
}
// 计算税前合计金额
const handleAmount = () => {
  const issuerRsult = formValue.laborInfoList.reduce((prev: any, dur: any) => {
    return prev + Number(dur.salary)
  }, 0)
  const customIssuerRsult = formValue.customIssuer.reduce((prev: any, dur: any) => {
    return prev + (dur.salary ? Number(dur.salary) : 0)
  }, 0)
  const result = (issuerRsult + customIssuerRsult) ? (issuerRsult + customIssuerRsult).toString() : '0'
  formValue.amount = result
}
// 添加发放人
const IssuerAdd = () => {
  formValue.laborInfoList.push({
    name: null, //姓名
    idCard: null, //身份证
    duty: null, //职务
    duration: null, //时长
    salary: null, //税前金额
    tax: '0', //预扣个税
    acquire: '0', //预计所得
    bankName: null, //开户银行
    bankId: null, //银行卡号
    phone: null //手机号码
  })
}
// 删除发放人
const deleteIssuer = (index: any) => {
  formValue.laborInfoList.splice(index, 1)
  handleAmount()
}
// 删除常用发放人
const deleteCustomIssuer = (index: any) => {
  formValue.customIssuer.splice(index, 1)
  handleAmount()
}
// 保存为常用发放人
const SaveIssuer = (index: any, flag: any) => {
  if (flag) {
    formRefUser.value[index]?.validate(async (err: any) => {
      if (err) return
      spinShow.value = true
      const [error, res] = await sendRequest({
        module: 'labor',
        api: 'saveCommonInfo',
        override: {
          data: {
            ...formValue.laborInfoList[index]
          }
        }
      })
      spinShow.value = false
      if (error) return message.error(error.message)
      if (res.code !== 0) return
      message.success('保存常用发布人成功')
      await getCommonInfoList()
      const id = commonInfoList.value.find((it: any) =>
        it.phone == formValue.laborInfoList[index].phone && it.name == formValue.laborInfoList[index].name)?.id
      if (id) formValue.laborInfoList[index].id = id
      formValue.customIssuer.unshift(formValue.laborInfoList[index])
      formValue.laborInfoList.splice(index, 1)
    })
  } else {
    formRefIssuer.value[index]?.validate(async (err: any) => {
      if (err) return
      spinShow.value = true
      const [error, res] = await sendRequest({
        module: 'labor',
        api: 'saveCommonInfo',
        override: {
          data: {
            ...formValue.customIssuer[index]
          }
        }
      })
      spinShow.value = false
      if (error) return message.error(error.message)
      if (res.code !== 0) return message.error(res.msg)
      message.success('保存常用发布人成功')
      await getCommonInfoList()
      const id = commonInfoList.value.find((it: any) =>
        it.phone == formValue.customIssuer[index].phone && it.name == formValue.customIssuer[index].name)?.id
      if (id) formValue.customIssuer[index].id = id
    })
  }
}
// 姓名校验
const renderName = (_: any, value: any) => {
  if (!value) return new Error('请输入姓名')
  if (value?.length > 10) return new Error('姓名字数不得超过10')
  return true
}
// 身份证校验
const renderIdCard = (_: any, value: any) => {
  if (!value) return new Error('请输入身份证号')
  if (value && !/^[1-9]\d{5}\d{4}((0[1-9])|(1[0-2]))((0[1-9])|([1-2]\d{1})|(3[0-1]))\d{3}(\d|X)$/g.test(value))
    return new Error('请输入正确格式的身份证号')
}
// 税前金额校验
const onlyFloatNumber = (value: any) => {
  var regA = /^\d*\.{0,1}\d{0,2}$/
  const tmp: any = value.split('')
  if (tmp[0] == 0 && tmp[1] == 0) return false
  return !value || regA.test(value)
}
// 开户银行校验
const renderBankName = (_: any, value: any) => {
  if (!value) return new Error('请输入开户银行')
  if (value?.length > 100) return new Error('开户银行字数不得超过100')
  return true
}
// 银行卡号校验
const renderBankId = (_: any, value: any) => {
  if (!value || value?.length === 0) return new Error('请输入银行卡号')
  return true
}
// 手机号码校验
const renderPhone = (_: any, value: any) => {
  if (!value) return new Error('请输入手机号')
  if (value && !/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/g.test(value))
    return new Error('请输入正确格式的手机号')
}
// 限制前后空格
const noSideSpace = (value: string) => !value.startsWith(' ') && !value.endsWith(' ')
// 获取流程id
const hint = ref()
const spinShow = ref(false)
const workFlowList = ref(' ')
const getWorkFlow = async (code: any) => {
  spinShow.value = true
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: code
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
  spinShow.value = false
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}
// 附件
const handleUploadList = (v: any) => (formValue.fileId = v)
// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const formRefIssuer: any = ref<FormInst | null>(null)
const formRefUser: any = ref<FormInst | null>(null)
const contentContent = ref()
const confirm = (status: any) => {
  formRef.value?.validate(async (err) => {
    if (err) return (contentVisible.value = false)
    const count = formValue.customIssuer?.length + formValue.laborInfoList?.length
    if (!count) return message.error('发放人不能为空')
    for (let i = 0; i < formRefUser.value?.length; i++) {
      await formRefUser.value[i]?.validate(async (err: any) => {
        if (err) return
      })
    }
    for (let i = 0; i < formRefIssuer.value?.length; i++) {
      await formRefIssuer.value[i]?.validate(async (err: any) => {
        if (err) return
      })
    }
    formValue.draft = status
    contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
    contentVisible.value = true
  })
}
// 提交
const contentVisible = ref(false)
const submit = async () => {
  const tmp = JSON.parse(JSON.stringify(formValue))
  tmp.laborInfoList = [...tmp.laborInfoList, ...tmp.customIssuer]
  delete tmp.customIssuer
  if ((props.id && props.flat) || (!props.id && !props.flat)) {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<OverTimeModel>>({
      module: 'labor',
      api: 'laborAdd',
      override: {
        data: tmp
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  } else {
    loading.value = true
    contentVisible.value = false
    const [error, res] = await sendRequest<HttpResponse<OverTimeModel>>({
      module: 'labor',
      api: 'laborUpdate',
      override: {
        data: {
          ...tmp,
          id: props.id
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success('保存成功')
  }
  goSubmit()
}
//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}
// 获取修改详情
const fileList: any = ref([])
const getDispatchInfo = async () => {
  const [error, res] = await sendRequest({
    module: 'labor',
    api: 'laborInfo',
    uri: {
      id: props.id
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  fileList.value = res.data.fileList
  Object.keys(formValue).map((it: any) => {
    if (it == 'entityId') return
    formValue[it] = res.data[it]
  })
  formValue.customIssuer = []
  formValue.laborInfoList.map((it: any, index: any) => {
    const i = commonInfoList.value.findIndex((c: any) => c.phone == it.phone && c.name == it.name)
    if (i !== -1) {
      it.id = commonInfoList.value[i].id
      formValue.customIssuer.push(it)
      formValue.laborInfoList.splice(index, 1)
    }
  })
}
//类型
const parentCodeList: any = ref([])
const getFunction = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'progress',
    api: 'parentCode',
    override: {
      params: {
        dicCode: 'A32'
      }
    }
  })
  if (error) return message.error(error.message)
  parentCodeList.value = res.data
}
// 获取常用发布人列表
const commonInfoList: any = ref()
const getCommonInfoList = async () => {
  const [error, res] = await sendRequest({
    module: 'labor',
    api: 'getCommonInfoList',
    override: {
      params: {
        page: 1,
        limit: 9999
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  commonInfoList.value = res.data.list
}

watch(
  () => props.id,
  async () => {
    if (props.title == '劳务费编辑' && props.id) {
      await getCommonInfoList()
      getDispatchInfo()
    }
  },
  { deep: true, immediate: true }
)

watch(() => formValue.amount, () => {
  if (formValue.amount < 10000) getWorkFlow('A0553')
  if (formValue.amount >= 10000 && formValue.amount < 300000) getWorkFlow('A0554')
  if (formValue.amount >= 300000) getWorkFlow('A0555')
}, { deep: true, immediate: true })

onMounted(() => {
  getFunction()
})
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.delectIcon {
  background-color: red;
  width: 25rem;
  height: 25rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  position: absolute;
  top: 50%;
  right: -40px;
  transform: translateY(-50%);
  cursor: pointer;
}

.amountClass {
  width: 100%;
  height: 35px;
  background-color: #fafafc;
  border: 1px solid #dfe0e5;
  font-style: 24px;
  display: flex;
  align-items: center;
  padding: 0 10px;
  white-space: nowrap;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;


      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 350rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 350rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
